package com.decade.qiyeshapan.service;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.decade.qiyeshapan.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

import org.springframework.context.annotation.Lazy;

@Service
public class MessageService {
    // 存储所有活跃的WebSocket会话（socketId -> session）
    private final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<>();

    @Autowired
    @Lazy
    private UserService userService;

    /**
     * 添加会话
     */
    public void addSession(WebSocketSession session) {
        String socketId = (String) session.getAttributes().get("socketId");
        if (socketId != null) {
            sessions.put(socketId, session);
        }
    }

    /**
     * 移除会话
     */
    public void removeSession(WebSocketSession session) {
        String socketId = (String) session.getAttributes().get("socketId");
        if (socketId != null) {
            sessions.remove(socketId);
        }
    }

    /**
     * 发送消息给指定用户
     */
    public void sendToUser(String socketId, String message) throws IOException {
        WebSocketSession session = sessions.get(socketId);
        if (session != null && session.isOpen()) {
            session.sendMessage(new TextMessage(message));
        }
    }

    /**
     * 广播给所有用户
     */
    public void broadcast(String message) throws IOException {
        for (WebSocketSession session : sessions.values()) {
            if (session.isOpen()) {
                session.sendMessage(new TextMessage(message));
            }
        }
    }

    public void broadcastToGame(String gameId, String message) {
        String key = "game:" + gameId;
        Map<String, User> users = userService.getAllUsers(gameId);
        
        users.values().stream()
            .map(User::getSocketId)
            .forEach(socketId -> {
                WebSocketSession session = sessions.get(socketId);
                if (session != null && session.isOpen()) {
                    try {
                        session.sendMessage(new TextMessage(message));
                    } catch (IOException e) {
                        System.err.println("发送消息到会话 " + socketId + " 失败: " + e.getMessage());
                    }
                }
            });
    }

    public void broadcastPlayerStatus(String gameId) {
        Map<String, User> users = userService.getAllUsers(gameId);
        JSONObject msg = JSONUtil.createObj()
                .set("type", "playerStatus")
                .set("players", users.values().stream()
                        .map(u -> JSONUtil.createObj()
                                .set("username", u.getUsername())
                                .set("isReady", u.isReady())
                        ).collect(Collectors.toList()));

        broadcastToGame(gameId, msg.toString());
    }
} 